#ifndef __MPC_H
#define __MPC_H

#include <stdint.h>
#include <stdlib.h>
#include <string.h>

#define HEADER1   0xAA
#define HEADER2   0x55

// 完整包大小：协议头(4字节) + data(len) + CRC16(2字节)
// 使用 uint8_t 类型进行运算，注意防止溢出
#ifdef ENABLE_CRC_CHECK
#define PACKET_TOTAL_SIZE(len) ((uint16_t)(6 + (len) + 2))  // 5: header(2)+cmd+subcmd+len, 2: CRC
// #define PACKET_CRC(pkt) (*((uint16_t *)((uint8_t *)(pkt) + 5 + (pkt)->length)))
#else
#define PACKET_TOTAL_SIZE(len) ((uint8_t)(6 + (len)))  // 5: header(2)+cmd+subcmd+len
#endif

#define SWAP_HIGH_LOW(x)   ( (((x) & 0x0F) << 4) | (((x) & 0xF0) >> 4) )

// header1 (1B) | header2 (1B) | command (1B) | subcmd (1B) | length (1B) | data[length] | CRC16 (2B)
typedef struct {
    uint8_t header1;   // 固定帧头 0xAA
    uint8_t header2;   // 固定帧头 0x55
    uint8_t srcdest;   // 目标+来源
    uint8_t cmd;       // 主命令
    uint8_t subcmd;    // 子命令
    uint8_t length;    // 数据长度（0~255）
    uint8_t data[];    // 实际数据内容
} protocol_packet_t;

typedef enum {
    PACKET_OK,
    PACKET_ERROR,
    PACKET_INCOMPLETE
} packet_parse_result_t;

packet_parse_result_t parse_protocol_packet(uint8_t *buf, uint16_t buf_len, protocol_packet_t **out_pkt);
protocol_packet_t *protocol_build_packet(uint8_t srcdest, uint8_t cmd, uint8_t subcmd, const uint8_t *data, uint8_t len);
uint16_t get_protocol_packet_size(const protocol_packet_t *pkt);
// void free_protocol_packet(protocol_packet_t *pkt);

#endif